// hyb_yl/backstageServices/pages/drupmespay/drupmespay.js
var app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    role: 0,
    cid: 0,
    steps: ["医生开方", "选择药品", "医生医嘱", '发送处方'],
    stepnum: 2,
    wenzhenpop: false,
    argeen: false,
    pay: "",
    noticedif: false,
    ifaddress: false,
    addressmes: {},
    num: 1,
    totals: 0,
    price: 0,
    cf_orser: 0,
    zid: 0,
    copyright: [{
        imgs: "https://6a69-jin5201-a4503e-1257013711.tcb.qcloud.la/renzheng.png?sign=99d87d2d65c67c848a10aaf43bafb66e&t=1583825248",
        text: "药监认证"
      },
      {
        imgs: "https://6a69-jin5201-a4503e-1257013711.tcb.qcloud.la/people.png?sign=717fc4019448bfc2a03ac538022f7ed8&t=1583825298",
        text: "药师审核"
      },
      {
        imgs: "https://6a69-jin5201-a4503e-1257013711.tcb.qcloud.la/yinsi.png?sign=f45888dbb9b06874e8d079f99d6018f5&t=1583825342",
        text: "隐私包装"
      },
    ],
    druplist: []
  },
  // 删除药品
  shanchu: function (e) {

  },
  //问诊协议
  wenzhenclick() {
    this.setData({
      wenzhenpop: true
    })
  },
  meknow() {
    this.setData({
      wenzhenpop: false
    })
  },
  // 是否同意协议
  radioChange() {
    this.setData({
      argeen: !this.data.argeen
    })
  },
  closewenzhenpop() {

  },
  // 注意事项
  noticedclick() {
    this.setData({
      noticedif: true
    })
  },
  closepop() {
    this.setData({
      noticedif: false
    })
  },
  //支付按钮
  paybtn(e) {
    var that = this
    var j_id = that.data.j_id
    var id = that.data.c_id
    var cid = that.data.cid
    var totals = e.currentTarget.dataset.totals //总价
    var back_orser = that.data.back_orser
    var useropenid = that.data.useropenid
    var key_words = that.data.key_words
    var zid = that.data.zid
    var cartlist = that.data.cartlist
    var zhenduan = that.data.zhenduan
    var yongyao = that.data.yongyao
    var text = that.data.text
    var tkid = app.globalData.tkid //一级
    var mytkid = app.globalData.mytkid //二级
    var cf_orser = that.data.cf_orser
    var goodstype = that.data.goodstype
    console.log(zid)
    wx.showModal({
      title: '是否发送',
      success: function (res) {
        var arr = {
          'text': text,
          'text1': zhenduan,
          'text2': yongyao
        }
        if (res.confirm) {
          //添加处方
          app.util.request({
            'url': 'entry/wxapp/goods.creatorder',
            data: {
              ifcf: 1,
              ifshop: 1,
              totalMoney: totals,
              back_orser: back_orser,
              openid: useropenid,
              key_words: key_words,
              goodarr: cartlist,
              j_id: j_id,
              cid: cid,
              zid: zid,
              conets: arr,
              cf_orser: cf_orser,
              goodstype: goodstype
            },
            success: function (res) {
              console.log(res)
              var orders = res.data
              //完成开方提醒
              app.util.request({
                'url': 'entry/wxapp/zhuanjia.chufangmsgdhs',
                data: {
                  id: orders,
                },
                success: function (res) {
                  console.log(res)
                }
              })
              app.util.request({
                'url': 'entry/wxapp/Studio.goodserweima',
                data: {
                  orders: orders,
                },
                success: function (res) {
                  console.log(res)
                },
              })

              //模板消息提醒
              app.util.request({
                'url': 'entry/wxapp/zhuanjia.chufangmobel',
                data: {
                  id: id,
                },
                success: function (res) {
                  console.log(res)
                }
              })
              app.util.request({
                'url': 'entry/wxapp/yuyue.kaiyaofanlis',
                data: {
                  back_orser: back_orser,
                },
                success: function (res) {
                  console.log(res)
                }
              })

              wx.showToast({
                title: '发送成功',
                icon: 'none',
                success: function () {
                  setTimeout(function () {
                    wx.reLaunch({
                      url: '/hyb_yl/mysubpages/pages/backstageIndex/backstageIndex'
                    })
                  }, 2000)
                }
              })
            }
          })
        }
      }
    })
    // wx.requestPayment({
    //   timeStamp: '',
    //   nonceStr: '',
    //   package: '',
    //   signType: '',
    //   paySign: '',
    // })
  },
  //加减
  aasbtnclick(e) {
    let types = e.currentTarget.dataset.types,
      num = this.data.num,
      totals = this.data.totals,
      price = this.data.price
    if (types == 'a') {
      ++num
    } else {
      num = num > 1 ? --num : 1
    }
    this.setData({
      num,
      totals: price * num
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    var goodstype = options.goodstype
    if (options.back_orser) {
      var cf_orser = options.back_orser
    } else {
      var cf_orser = 0
    }


    if (options.zid) {
      var zid = options.zid
    } else {
      var zid = 0

    } //c_id=23&text=ceeeeeeeeeeeeeeeeeeeeeeeeeeee1&zhenduan=dsfsdf&j_id=60&yongyao=sdfsdfs&role=1&inquiry=&conets=undefined&key_words=yuanchengkaifang

    // var cartlist = options.cartlist;
    var ifzj = options.ifzj
    var role = options.role
    var inquiry = options.inquiry
    var key_words = options.key_words
    var jiaqianArr = []
    var listgoodArr = []
    var c_id = options.c_id
    var orders = options.orders
    if (role == 1) {
      var cid = 1
    } else {
      var cid = 0
    }
    app.util.request({
      'url': 'entry/wxapp/hzbingli.url',
      success: function (res) {
        console.log(res)
        that.setData({
          url: res.data,
        })
      }
    })


    if (options.orders) {
      that.setData({
        orders: orders
      })
    }
    if (options.role == '1') {
      var cartlist = wx.getStorageSync('cartlist')
      for (var i = 0; i < cartlist.length; i++) {
        listgoodArr.push(cartlist[i].sid);
      }
      for (var i = 0; i < cartlist.length; i++) {
        var jiaqian = (cartlist[i].num * 1) * (cartlist[i].smoney * 1)
        jiaqianArr.push(jiaqian)
      }
      var result = 0;
      for (var i = 0; i < jiaqianArr.length; i++) {
        result += jiaqianArr[i] * 1;
      }
      console.log(result)
      that.setData({
        cartlist: cartlist,
        totals: result.toFixed(2)
      })
    } else {
      var goodsid = options.goodsid;
      that.setData({
        goodsid: goodsid
      })
      app.util.request({
        'url': 'entry/wxapp/zhuanjia.chufanggoods',
        'data': {
          back_orser: orders,
          c_id: c_id,
          goodsid: goodsid
        },
        success: function (res) {
          console.log('药品')
          console.log(res.data);
          var cartlist = res.data.cartlist ? res.data.cartlist : wx.getStorageSync('cartlist');

          console.log(cartlist)
          for (var i = 0; i < cartlist.length; i++) {
            listgoodArr.push(cartlist[i].sid);
          }
          for (var i = 0; i < cartlist.length; i++) {
            var jiaqian = (cartlist[i].num * 1) * (cartlist[i].smoney * 1)
            jiaqianArr.push(jiaqian)
          }
          var result = 0;
          for (var i = 0; i < jiaqianArr.length; i++) {
            result += jiaqianArr[i] * 1;
          }
          console.log(result)
          that.setData({
            cartlist: cartlist,
            totals: result.toFixed(2)
          })
        }
      })

    }

    if (options.text !== undefined) {
      var text = options.text //描述
    } else {
      var textARR = JSON.parse(options.conets)

      var text = textARR.text
    }

    var zhenduan = options.zhenduan //诊断
    var j_id = options.j_id
    var yongyao = options.yongyao //用药
    var bgc = wx.getStorageSync('color')
    wx.setNavigationBarColor({
      frontColor: "#ffffff",
      backgroundColor: bgc,
    })
    //远程开方
    if (key_words == 'yuanchengkaifang') {
      app.util.request({
        'url': 'entry/wxapp/zhuanjia.getcfdetail',
        data: {
          c_id: c_id,
          cf_orser: cf_orser
        },
        success: function (res) {
          console.log(res)
          var info = res.data
          that.setData({
            info: info,
            useropenid: info.useropenid,
            back_orser: info.back_orser,
            key_words: info.key_words
          })
        }
      })
    }
    //图文问诊
    if (key_words == 'tuwenwenzhen') {
      app.util.request({
        'url': 'entry/wxapp/zhuanjia.gettwdetail',
        data: {
          id: c_id,
          cf_orser: cf_orser
        },
        success: function (res) {
          console.log(res)
          var info = res.data
          that.setData({
            info: info,
            useropenid: info.openid,
            back_orser: info.back_orser,
            key_words: that.data.key_words
          })
        }
      })
    }
    //视频问诊
    if (key_words == 'shipinwenzhen') {
      app.util.request({
        'url': 'entry/wxapp/zhuanjia.gettwzetail',
        data: {
          id: c_id,
          cf_orser: cf_orser
        },
        success: function (res) {
          console.log(res)
          var info = res.data
          that.setData({
            info: info,
            useropenid: info.openid,
            back_orser: info.back_orser,
            key_words: info.key_words
          })
        }
      })
    }
    //电话问诊
    if (key_words == 'dianhuajizhen') {
      app.util.request({
        'url': 'entry/wxapp/zhuanjia.gettwzetail',
        data: {
          id: c_id,
          cf_orser: cf_orser
        },
        success: function (res) {
          console.log(res)
          var info = res.data
          that.setData({
            info: info,
            useropenid: info.openid,
            back_orser: info.back_orser,
            key_words: info.key_words
          })
        }
      })
    }
    app.util.request({
      'url': 'entry/wxapp/user.detail',
      data: {
        j_id: j_id
      },
      success: function (res) {
        console.log(res)
        that.setData({
          userdeta: res.data
        })
      }
    })
    if (options.conets) {
      var conets = options.conets
      that.setData({
        conets: conets
      })
    }
    that.setData({
      pay: options.pay,
      //cartlist: cartlist,
      c_id: c_id,
      text: text,
      zhenduan: zhenduan,
      j_id: j_id,
      yongyao: yongyao,
      role: role,
      ifzj: ifzj,
      inquiry: inquiry,
      listgoodArr: listgoodArr,
      key_words: key_words,
      cf_orser: cf_orser,
      zid: zid,
      goodstype: goodstype
    })
  },
  //添加地址
  address() {
    let self = this;

    var listgoodArr = self.data.listgoodArr
    var cartlist = self.data.cartlist
    var arr1 = []
    var region = [];
    for (var i = 0; i < cartlist.length; i++) {
      arr1.push({
        num: cartlist[i].num,
        yf_id: cartlist[i].yf_id,
      })
    }
    wx.chooseAddress({
      success(res) {
        console.log("res")
        console.log(res)
        console.log(JSON.stringify(res))
        var name = res.userName
        var phone = res.telNumber
        region.push(res.provinceName, res.cityName, res.countyName)
        var address = res.detailInfo
        var addlist = {
          name: res.userName,
          phone: res.telNumber,
          address: res.detailInfo,
          region: region,
          label: -1,
          addlabel: ""
        }
        console.log(addlist)
        //添加收货人信息
        var userName = addlist.name
        var userPhone = addlist.phone
        var userAddress = addlist.region[0] + '-' + addlist.region[1] + '-' + addlist.region[2] + '-' + addlist.address
        app.util.request({
          'url': 'entry/wxapp/goods.creatuseraddress',
          data: {
            openid: wx.getStorageSync('openid'),
            userName: userName,
            userPhone: userPhone,
            userAddress: userAddress
          },
          success: function (res) {
            console.log(res)
            var addressid = res.data.addressId
            wx.setStorageSync("Address", res.data)
            self.setData({
              addressid: addressid,
              addresslist: res.data
            })
            if (res.data == "") {
              self.setData({
                addbox: true
              })
            } else {
              self.setData({
                addbox: false
              })
            }
          }
        })
        arr1 = wx.getStorageSync("Address") || [];
        self.setData({
          addresslist: arr1
        })
        let obj = {
          name: res.userName,
          tell: res.telNumber,
          site: res.provinceName + res.cityName + res.countyName + res.detailInfo
        }
        var provinceName = res.provinceName
        self.setData({
          ifaddress: true,
          addressmes: obj,
          provinceName: res.provinceName
        })
        //计算运费
        app.util.request({
          'url': 'enter/wxapp/wuliu.peisong',
          data: {
            provinceName: provinceName,
            listgoodArr: arr1
          },
          success: function (res) {
            var cartlist = res.data
            //  console.log(cartlist)
            // self.setData({
            //   cartlist: res.data
            // })
          }
        })
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   * 
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  //加 减
  handleNumberClick(e) {
    let types = e.currentTarget.dataset.type,
      i = e.currentTarget.dataset.dex,
      id = e.currentTarget.dataset.id,
      cratlist = this.data.cartlist,
      self = this
    if (types == 'add') {
      ++cratlist[i].num
    } else if (types == 'reduce') {
      if (cratlist[i].num == 1) {
        return
      }
      --cratlist[i].num
    }
    if (cratlist.length == 0) {
      self.setData({
        cartpop: false
      })
    }
    this.setData({
      cartlist: cratlist
    })


    var jiaqianArr = []
    for (let i = 0; i < cratlist.length; i++) {
      var jiaqian = (cratlist[i].num * 1) * (cratlist[i].smoney * 1)
      // console.log(jiaqian)
      jiaqianArr.push(jiaqian)
    }
    var result = 0;
    for (let i = 0; i < jiaqianArr.length; i++) {
      result += jiaqianArr[i] * 1;
    }
    //console.log(result)
    this.setData({
      totals: result.toFixed(2)
    })

  },
  //删除购物车
  deletedrup(e) {
    let i = e.currentTarget.dataset.dex,
      cratlist = this.data.cartlist,
      id = e.currentTarget.dataset.id
    cratlist.splice(i, 1)
    if (cratlist.length == 0) {
      this.setData({
        cartpop: false
      })
    }
    this.setData({
      cartlist: cratlist,
    })
  },
  tainjiayaopin: function (e) {
    var pages = getCurrentPages();
    var prevPage = pages[pages.length - 2]; //上一个页面
    //直接调用上一个页面的setData()方法，把数据存到上一个页面中去
    console.log(prevPage.data.druplist)
    var druplist = prevPage.data.druplist
    for (var i = 0; i < druplist.length; i++) {
      druplist[i].num = 0
    }
    var druplist = druplist
    prevPage.setData({
      druplist: druplist,
      cartlist: [],
      sum: 0
    })

    wx.navigateBack({
      delta: 1
    })

  },
  payordercf(e) {
    var that = this
    var money = parseFloat(e.currentTarget.dataset.totals)
    var uniacid = app.siteInfo.uniacid
    var orders = that.data.orders

    var addressmes = that.data.addressmes
    var cartlist = that.data.cartlist
    var addressid = that.data.addressid
    var role = that.data.role
    console.log(money);
    var arr1 = []
    for (var i = 0; i < cartlist.length; i++) {
      arr1.push({
        sname: cartlist[i].sname,
        smoney: cartlist[i].smoney,
        snum: cartlist[i].snum,
        sthumb: cartlist[i].sthumb,
        num: cartlist[i].num,
        sid: cartlist[i].sid,
        s_id: cartlist[i].s_id,
        yf_id: cartlist[i].yf_id,
      })
    }

    var inquiry = that.data.inquiry
    console.log(inquiry);
    if (!addressmes.name) {
      wx.showToast({
        title: '请选择地址',
        icon: 'none'
      })
      return false;
    }
    if (inquiry == '4') {
      //添加新的处方订单
      var conets = JSON.parse(that.data.conets)
      app.util.request({
        'url': 'entry/wxapp/zhuanjia.addchufangxq',
        data: {
          openid: wx.getStorageSync('openid'),
          key_words: 'yuanchengkaifang',
          arr: conets,
          cartlist: arr1,
          j_id: that.data.j_id,
          totals: money,
          cid: 0,
          addressid: addressid,
          role: 1,
          goodsid: that.data.goodsid
        },
        success: function (res) {
          console.log(res)
          var orderno = res.data.orderNo
          app.util.request({
            'url': 'entry/wxapp/yuyue.paycforder',
            header: {
              "Content-Type": "application/xml"
            },
            method: "GET",
            data: {
              openid: wx.getStorageSync('openid'),
              z_tw_money: money,
              orders: orderno,
            },
            success: function (res) {
              console.log(res);
              wx.requestPayment({
                'timeStamp': res.data.timeStamp,
                'nonceStr': res.data.nonceStr, //字符串随机数
                'package': res.data.package,
                'signType': res.data.signType,
                'paySign': res.data.paySign,
                success: function (res) {
                  console.log(res)
                  //提醒医生
                  app.util.request({
                    'url': 'entry/wxapp/yuyue.upchufangwentype',
                    data: {
                      orders: orderno,
                    },
                    success: function (res) {
                      console.log(res)

                    }
                  })

                  app.util.request({
                    'url': 'entry/wxapp/zhuanjia.addchufangxq',
                    data: {
                      openid: wx.getStorageSync('openid'),
                      key_words: 'yuanchengkaifang',
                      arr: conets,
                      cartlist: arr1,
                      j_id: that.data.j_id,
                      totals: money,
                      cid: 0,
                      addressid: addressid,
                      role: role,
                      orders: orders,
                      goodsid: that.data.goodsid
                    },
                    success: function (res) {
                      console.log(res)
                    }
                  })

                  app.util.request({
                    'url': 'entry/wxapp/yuyue.upcforderadd',
                    header: {
                      "Content-Type": "application/xml"
                    },
                    method: "GET",
                    data: {
                      orders: orderno,
                      addressmes: addressmes
                    },
                    success: function (res) {
                      wx.navigateTo({
                        url: '/hyb_yl/userCommunicate/pages/order/order',
                      })
                    }
                  })
                },
                fail: function (res) {
                  console.log(res)
                  wx.navigateTo({
                    url: '/hyb_yl/userCommunicate/pages/order/order',
                  })

                }
              })
            }
          })
          // app.util.request({
          //   'url': 'entry/wxapp/yuyue.paycforder',
          //   header: {
          //     "Content-Type": "application/xml"
          //   },
          //   method: "GET",
          //   data: {
          //     openid: wx.getStorageSync('openid'),
          //     z_tw_money: money,
          //     orders: orderno,
          //   },
          //   success: function (res) {
          //     console.log(res);
          //     wx.requestPayment({
          //       'timeStamp': res.data.timeStamp,
          //       'nonceStr': res.data.nonceStr, //字符串随机数
          //       'package': res.data.package,
          //       'signType': res.data.signType,
          //       'paySign': res.data.paySign,
          //       success: function (res) {
          //         console.log(res)
          //         //提醒医生
          //         app.util.request({
          //           'url': 'entry/wxapp/yuyue.upchufangwentype',
          //           data: {
          //             orders: orderno,
          //           },
          //           success: function (res) {
          //             console.log(res)

          //           }
          //         })
          //         app.util.request({
          //           'url': 'entry/wxapp/yuyue.upcforderadd',
          //           header: {
          //             "Content-Type": "application/xml"
          //           },
          //           method: "GET",
          //           data: {
          //             orders: orderno,
          //             addressmes: addressmes
          //           },
          //           success: function (res) {
          //             wx.navigateTo({
          //               url: '/hyb_yl/userCommunicate/pages/order/order',
          //             })
          //           }
          //         })
          //       },
          //       fail: function (res) {
          //         console.log(res)
          //         wx.navigateTo({
          //           url: '/hyb_yl/userCommunicate/pages/order/order',
          //         })

          //       }
          //     })
          //   }
          // })
        }
      })




    } else {
      console.log('222')
      console.log(money)
      console.log(orders)
      app.util.request({
        'url': 'entry/wxapp/yuyue.paycforder',
        header: {
          "Content-Type": "application/xml"
        },
        method: "GET",
        data: {
          openid: wx.getStorageSync('openid'),
          z_tw_money: money,
          orders: orders,
        },
        success: function (res) {
          console.log(res);
          wx.requestPayment({
            'timeStamp': res.data.timeStamp,
            'nonceStr': res.data.nonceStr, //字符串随机数
            'package': res.data.package,
            'signType': res.data.signType,
            'paySign': res.data.paySign,
            success: function (res) {
              console.log(res)
              //提醒医生

              //修改处方订单
              app.util.request({
                'url': 'entry/wxapp/zhuanjia.addchufangxq',
                data: {
                  openid: wx.getStorageSync('openid'),
                  key_words: 'yuanchengkaifang',
                  arr: conets,
                  cartlist: arr1,
                  j_id: that.data.j_id,
                  totals: money,
                  cid: 0,
                  addressid: addressid,
                  role: role,
                  orders: orders,
                  goodsid: that.data.goodsid
                }
              })

              //更新订单地址
              app.util.request({
                'url': 'entry/wxapp/yuyue.upcforderadd',
                header: {
                  "Content-Type": "application/xml"
                },
                method: "GET",
                data: {
                  orders: orders,
                  addressmes: addressmes
                },
                success: function (res) {
                  wx.navigateTo({
                    // url: '/hyb_yl/mysubpages/pages/my_hzprescription/my_hzprescription',
                    url: '/hyb_yl/userCommunicate/pages/order/order',
                  })
                }
              })
            },
            fail: function (res) {
              console.log(res)
            }
          })
        }
      })
    }

  }
})